Add Two Numbers

03-11-17 Course- CPP

#include <iostream>
using namespace std;

int main() {
    float n1, n2, sum;
    cout << "Enter two numbers: ";
    cin >> n1 >> n2;
    sum = n1+n2;
    cout << "Sum = " << sum;
    return 0;
}

Output


Enter two numbers: 3.4
2.3
Sum = 5.7

In this program, user is asked to enter two numbers which is stored in n1 and n2 respectively. The + operator is used for adding these two numbers and result is stored in variable sum. Finally, the sum is displayed and program is terminated.

You can also perform this task using two variables by assigning sum of two variables to either n1 or n2.


#include <iostream>
using namespace std;

int main() {
    float n1, n2;
    cout << "Enter two numbers: ";
    cin >> n1 >> n2;
    n1 = n1+n2;
    cout << "Sum = " << n1;
    return 0;
}